package demo;

import java.time.LocalDateTime;

import com.aerospike.client.Bin;
import com.aerospike.client.IAerospikeClient;
import com.aerospike.client.Key;
import com.aerospike.client.Record;
import com.aerospike.client.policy.GenerationPolicy;
import com.aerospike.client.policy.WritePolicy;

public class GenerationTest {
	static String namespace = "ns1";
	static String dataSetName = "testset";
	static String bin = "DATA";
	static String key = "generation_test";

	public static void main(String[] args) throws Exception {

		IAerospikeClient client = AsClientUtil.getClient();
		System.out.println("client=" + client);

		delete(client, key);
		String value = LocalDateTime.now().toString();

		try {
			update(client, key, value, -1);
		} catch (Throwable e) {
			// com.aerospike.client.AerospikeException: Error Code 3: Generation error
			System.out.println(e);
		}
		try {
			update(client, key, value, 1);
		} catch (Throwable e) {
			System.out.println(e);
		}
		// create generation 0
		update(client, key, value, 0);

		System.out.println(get(client, key));

		for (int i = 1; i <= 3; i++) {
			update(client, key, value + "_" + i, i);
			System.out.println(get(client, key));
		}

	}

	private static Record get(IAerospikeClient client, String key) throws Exception {
		Key k = new Key(namespace, dataSetName, key);
		return client.get(null, k);
	}

	private static void delete(IAerospikeClient client, String key) throws Exception {
		Key k = new Key(namespace, dataSetName, key);
		client.delete(null, k);
	}

	private static void update(IAerospikeClient client, String key, String value, int generation) throws Exception {

		Key k = new Key(namespace, dataSetName, key);
		Bin b = new Bin(bin, value);
		WritePolicy policy = new WritePolicy();
		policy.generationPolicy = GenerationPolicy.EXPECT_GEN_EQUAL;
		policy.generation = generation;

		client.put(policy, k, b);
	}

}
